#encoding=utf-8

import datetime
import time
import urllib
import ujson

from django.contrib import admin
from django.db.models import Count, Max, F, Sum
from django.db.models.query import QuerySet
from django.utils.safestring import mark_safe
from django.utils.html import format_html
from django.contrib.auth.views import login
from django.contrib.auth.models import User

from django import forms
from django.utils.translation import ugettext, ugettext_lazy as _

from websys.models import (
    UserProfile, HXHUserInfo, HXHPayInfo,PlatformInfo,HXHUserLogin,HXHConsumerInfo,
AgentInfo,UserInfo,GameInfo,RoomInfo,
)

import xadmin
from xadmin.views.list import ResultRow, ResultItem
from websys.admin.AdminLoginForm import AdminAuthenticationForm
from xadmin.views import website
from myfilter import AgentFilter
from websys import webconfig

website.LoginView.login_form = AdminAuthenticationForm
# Register your models here.

class UserCreationForm(forms.ModelForm):
    mycid = forms.CharField(label=_("Mycid"), widget=forms.HiddenInput)
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'password_mismatch': _("Error,The two password fields didn't match."),
        'add_forbid': _("can not add next agent."),
         'blank_parent': _("parent not blank."),
        'comrate_error': _("comrate not more than %(par)s"),
    }

    def clean_uid(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["uid"]
        try:
            UserInfo._default_manager.get(uid=username)
        except UserInfo.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

    def clean_agentid(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.

        par_info = self.cleaned_data["agentid"]
        ag_info=self.instance
        #print(th_rate,self.instance,'---clean_comrate---',self.data,dir(self))
        parid = ag_info.agentid#self.cleaned_data["parentid"]

        if not par_info:#代理登陆进去时添加不能为空
            login_cid=self.data['mycid']
            if len(login_cid)>0:
                #print(dir(self),'*************clean_agentid------------------',self.cleaned_data,self.data,dir(ag_info))
                raise forms.ValidationError(self.error_messages['blank_parent'])

        return par_info

    def save(self, commit=True):
        user = super(UserInfoAdmin, self).save(commit=False)
        if commit:
            user.save()
        return user

class ParFilter(AgentFilter):

    def __init__(self, request, params, model, admin_view):

        self.used_params = {}
        self.request = request
        self.params = params
        self.model = model
        self.admin_view = admin_view
        #self.lookup_choices=[]

        super(ParFilter,self).__init__(request, params, model, admin_view,'_p_agentid__id__exact','agentid')


#用户页面
class UserInfoAdmin(object):
    def oper_point(self, obj):#自定义列
        return u'<span style="color:red;font-weight:bold" id="sp_point_{0}">{1}</span>' .format (obj.pk,obj.gamepoint)

    oper_point.short_description = u'金币'
    oper_point.allow_tags = True

    def image_tag(self, obj):
        t_url=obj.head_img
        if(t_url.find('http://')==-1):
            t_url="/"+t_url
        return format_html('<img src="{}" style="width:90px;height:60px;" />'.format(t_url))
    image_tag.short_description = '头像'

    def status_state(self, obj):#自定义列
        if obj.status == 0:
            return u'<span style="color:red;font-weight:bold">{0}</span>'.format(u"黑名单")
        elif obj.status == 1:
            return u'<span style="color:green;font-weight:bold">{0}</span>'.format(u"正常")
        else:
            return u'<span style="color:orange;font-weight:bold">%s</span>' % (u"其它",)
    status_state.short_description = u'状态'
    status_state.allow_tags = True

    def oper_column(self,obj):
        # t_html=u'<button type="button" id="my_point_{0}" class="btn btn-success" autocomplete="off"' \
        #            u' onclick="oper_point(\'#my_point_{0}\', \'{0}\', \'{3}\', \'{2}\')">{1}</button>&nbsp;&nbsp;' .format (obj.pk,"充值",obj.gamepoint,obj.nickname)
        if webconfig.RECHARGE_DELELTE:
            t_html=u'<button type="button" id="my_point_{0}" class="btn btn-success" autocomplete="off"' \
                       u' onclick="oper_point(\'#my_point_{0}\', \'{0}\', \'{3}\', \'{2}\',\'{4}\')">{1}</button>&nbsp;&nbsp;' .format (obj.pk,"充值",obj.gamepoint,obj.nickname,0)
            t_html += u'<button type="button" id="my_point_{0}" class="btn btn-success" autocomplete="off"' \
                       u' onclick="oper_point(\'#my_point_{0}\', \'{0}\', \'{3}\', \'{2}\',\'{4}\')">{1}</button>&nbsp;&nbsp;' .format (obj.pk,"回收",obj.gamepoint,obj.nickname,1)
        else:
            t_html = u'<button type="button" id="my_point_{0}" class="btn btn-success" autocomplete="off"' \
                           u' onclick="oper_point(\'#my_point_{0}\', \'{0}\', \'{3}\', \'{2}\')">{1}</button>&nbsp;&nbsp;' .format (obj.pk,"充值",obj.gamepoint,obj.nickname)
        if self.user.is_superuser:
            if obj.status == 0:
                t_html+= u'<button type="button" id="my_status_{0}" class="btn btn-success" autocomplete="off"' \
                       u' onclick="oper_status(\'#my_status_{0}\', \'{0}\', \'{1}\', \'{4}\')">{2}</button>' .format (obj.pk,1,"还原",u"黑名单",obj.nickname)
            elif obj.status == 1:
                t_html+=u'<button type="button" id="my_status_{0}" class="btn btn-success" autocomplete="off"' \
                       u' onclick="oper_status(\'#my_status_{0}\', \'{0}\', \'{1}\', \'{4}\')">{2}</button>' .format (obj.pk,0,"拉黑","正常",obj.nickname)
            else:
                pass
        return t_html
    oper_column.short_description = u'操作'
    oper_column.allow_tags = True

    list_display=('uid', 'nickname', 'agentid','create_time','image_tag','gamepoint','status_state','oper_column')
    search_fields=('uid', 'agentid__account', 'nickname')
    list_filter = ('uid',ParFilter)
    fields=('uid', 'agentid', 'nickname','gender','phone')#只显示可编辑的列
    list_exclude = ("id",'gamepoint','status','password','pf','head_img')
    raw_id_fields = ('agentid',)

    def get_list_display(self):
         list_display = super(UserInfoAdmin, self).get_list_display()
         # if not self.user.is_superuser and (not self.user.groups.filter(pk=webconfig.ADMIN_AGENT_GROUP_ID).count()==1):
         #     list_display.remove('oper_column')
         return list_display

    def get_readonly_fields(self):
        if hasattr(self,"org_obj") and (self.org_obj is not None):#修改状态下
            return ('uid', 'agentid')
        return ()

    #添加资源
    def get_media(self):
        #<div id="type-dialogBox"></div>
        media = super(UserInfoAdmin, self).get_media()
        #media.add_html('<div id="type-dialogBox"></div>')http://libs.baidu.com/jquery/1.11.1/jquery.min.js
        #media.add_css((self.static('jquery_dialogbox.css'),))
        #media.add_css({'screen':self.static('jquery-ui.min.css')})
        media.add_css({'screen': ['css/jquery-ui.min.css']})
        media.add_js((self.static('js/jquery.min.js'),))
        media.add_js((self.static('js/jquery-ui.min.js'),))
        #media.add_js((self.static('js/jquery.dialogbox.js'),))
        media.add_js((self.static('UserInfoAdminAdmin.js'),))
        media.add_js((self.static('ButtonControl.js'),))
        return media

    #重写编辑页面
    def get_model_form(self, **kwargs):
        if self.org_obj is None:
            self.form = UserCreationForm

        return super(UserInfoAdmin, self).get_model_form(**kwargs)

    #根据classid找下线
    def queryset(self):
        login_uid = self.user.username
        queryset_all = super(UserInfoAdmin, self).queryset()
        if AgentInfo.objects.filter(account=login_uid).exists():#是代理
            a_info=AgentInfo.objects.get(account=login_uid)
            if webconfig.RECHARGE_DELELTE:
                qs = queryset_all.filter(agentid__classid=a_info.classid)  # .exclude(agentid__account=login_uid)#like classid%
            else:
                qs = queryset_all.filter(agentid__classid__startswith=a_info.classid)#.exclude(agentid__account=login_uid)#like classid%
            #UserInfo.objects.annotate(su).exclude(agentid__account=)
            return qs
        return queryset_all


    def formfield_for_dbfield(self, db_field, **kwargs):#重写编辑列显示
        if db_field.get_attname() == "agentid_id":#只获取自己下线
            login_uid = self.user.username
            if AgentInfo.objects.filter(account=login_uid).exists():#是代理
                a_info=AgentInfo.objects.get(account=login_uid)
                kwargs["queryset"] = AgentInfo.objects.filter(classid__startswith=a_info.classid)#.exclude(account=login_uid)
        return super(UserInfoAdmin, self).formfield_for_dbfield(db_field, **kwargs)

#玩家的渲染的
xadmin.site.register(UserInfo, UserInfoAdmin)